{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>文件管理系统</title>
    <link rel="icon" href="{% static 'img/favicon.ico' %}">
    <link rel="stylesheet" href="{% static 'bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css' %}">
    <!-- 本地引入Font Awesome加载 -->
    <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}" onerror="this.remove()">
    <!--  自定义样式 -->
    <!--<link rel="stylesheet" href="{% static 'css/custom.css' %}">-->
</head>
<body>
    <!-- 头部信息 -->
    <nav class="navbar navbar-dark bg-primary">
        <div class="container">
            <div class="d-flex align-items-center w-100">
                <div class="d-flex align-items-center">
                    <a class="navbar-brand me-3" href="/">
                        <img src="{% static 'img/logo.png' %}" alt="Logo" height="30" class="d-inline-block align-text-top me-2">
                        文件管理系统
                    </a>
                    <button class="btn btn-outline-light me-2" id="mobile-view">
                        <i class="fa fa-mobile-alt me-2"></i>手机浏览 <i class="fa fa-qrcode"></i>
                    </button>
                </div>
                <div class="ms-auto d-flex align-items-center">
                    <form method="get" class="d-flex me-3" id="navSearchForm">
                        <input type="search" name="q" value="{{ request.GET.q }}" 
                               class="form-control" placeholder="Search..." id="navSearchInput">
                        <button class="btn btn-outline-light ms-2" type="submit">
                            <i class="fa fa-search"></i>
                        </button>
                    </form>
                    <a href="/admin/" class="btn btn-outline-light" target="_blank" rel="noopener noreferrer">登录</a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 面包屑导航 -->
    <div class="container mt-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="/"><i class="fa fa-home me-1"></i>首页</a></li>
                {% if breadcrumbs %}
                    {% for crumb in breadcrumbs %}
                        <li class="breadcrumb-item"><a href="{{ crumb.url }}"><i class="fa fa-folder me-1"></i>{{ crumb.name }}</a></li>
                    {% endfor %}
                {% endif %}
            </ol>
        </nav>
    </div>

    <!-- 内容区域 -->
    <div class="container mt-2">
        {% block content %}{% endblock %}
    </div>

    <!-- 底部信息 -->
    <div class="fixed-bottom text-center mb-2 text-muted small">
        Copyright © 2025 <a href="https://gitcode.com/ibobcheung/PythonFileHttpServer" target="_blank">文件管理系统 v1.0.0</a> | Powered by <a href="https://www.pheks.com" target="_blank">Mr. Z</a> | 电子邮箱: <a href="mailto:<EMAIL>">bob@pheks.com</a>
    </div>
    <!-- 本地引入bootstrap.min.js -->
    <script src="{% static 'bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js' %}"></script>
    
    <style>
        .fa {
            font-size: 1.1em;
            vertical-align: middle;
        }
    </style>
    <!-- 本地引入qrcode.min.js -->
    <script src="{% static 'js/qrcode.min.js' %}"></script>
    <!-- Office预览库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.0/mammoth.browser.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script>
        // 初始化Office预览功能
        const OfficePreview = {
            renderDoc: function(arrayBuffer, containerId) {
                // 使用Mammoth.js渲染Word文档
                mammoth.extractRawText({arrayBuffer: arrayBuffer})
                    .then(function(result) {
                        const container = document.getElementById(containerId);
                        container.innerHTML = `<pre style="white-space: pre-wrap;">${result.value}</pre>`;
                    })
                    .catch(function(error) {
                        console.error(error);
                        document.getElementById(containerId).innerHTML = 
                            '<p class="text-danger">文档预览失败</p>';
                    });
            },
            renderXls: function(arrayBuffer, containerId) {
                // 使用SheetJS渲染Excel
                try {
                    const data = new Uint8Array(arrayBuffer);
                    const workbook = XLSX.read(data, {type: 'array'});
                    const container = document.getElementById(containerId);
                    container.innerHTML = XLSX.utils.sheet_to_html(workbook.Sheets[workbook.SheetNames[0]]);
                } catch(e) {
                    console.error(e);
                    document.getElementById(containerId).innerHTML = 
                        '<p class="text-danger">表格预览失败</p>';
                }
            },
            renderPpt: function(arrayBuffer, containerId) {
                // 简单提示PPT需要转换为PDF预览
                document.getElementById(containerId).innerHTML = 
                    '<p class="text-muted">PPT文件请下载后使用本地软件查看</p>';
            }
        };
    </script>
    <style>
        .qr-loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,.3);
            border-radius: 50%;
            border-top-color: #000;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
    <script>
        function showQRCode() {
            // 获取当前页面URL
            const fullUrl = window.location.href;
            
            // 检查URL有效性
            if (!fullUrl || fullUrl === window.location.origin) {
                alert('当前页面URL无效，无法生成二维码');
                return;
            }

            console.log('正在生成二维码，URL:', fullUrl); // 调试信息

            try {
                // 创建弹窗
                const dialog = document.createElement('div');
                dialog.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.7);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 9999;
                `;
            
                // 弹窗内容
                const content = document.createElement('div');
                content.style.cssText = `
                    background: white;
                    padding: 20px;
                    border-radius: 10px;
                    text-align: center;
                    max-width: 90%;
                `;
                
                const title = document.createElement('h5');
                title.textContent = '手机扫描访问';
                title.style.marginBottom = '15px';
                
                const qrCode = document.createElement('div');
                qrCode.id = 'qrcode';
                qrCode.style.margin = '0 auto';
                
                // 加载状态
                const loading = document.createElement('div');
                loading.className = 'qr-loading';
                loading.style.margin = '20px auto';
                
                const closeBtn = document.createElement('button');
                closeBtn.className = 'btn btn-secondary mt-3';
                closeBtn.textContent = '关闭';
                closeBtn.onclick = () => {
                    document.body.removeChild(dialog);
                    console.log('二维码弹窗已关闭');
                };
                
                content.appendChild(title);
                content.appendChild(loading);
                content.appendChild(closeBtn);
                dialog.appendChild(content);
                document.body.appendChild(dialog);
                
                // 生成二维码
                setTimeout(() => {
                    try {
                        content.removeChild(loading);
                        new QRCode(qrCode, {
                            text: fullUrl,
                            width: 200,
                            height: 200,
                            colorDark: "#000000",
                            colorLight: "#ffffff",
                            correctLevel: QRCode.CorrectLevel.H
                        });
                        console.log('二维码生成成功');
                        content.insertBefore(qrCode, closeBtn);
                    } catch (e) {
                        console.error('二维码生成失败:', e);
                        content.removeChild(loading);
                        const error = document.createElement('p');
                        error.textContent = '二维码生成失败: ' + e.message;
                        error.style.color = 'red';
                        content.insertBefore(error, closeBtn);
                    }
                }, 100);
            } catch (error) {
                console.error('生成二维码弹窗时出错:', error);
                alert('生成二维码时出错: ' + error.message);
            }
        }

        // 确保DOM加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', function() {
            const mobileViewBtn = document.getElementById('mobile-view');
            if (mobileViewBtn) {
                mobileViewBtn.addEventListener('click', showQRCode);
                console.log('已绑定手机浏览按钮点击事件');
            } else {
                console.error('未找到手机浏览按钮');
            }
        });

        function showDownloadQR(element) {
            // 确保中文路径正确编码
            const downloadUrl = decodeURIComponent(element.getAttribute('data-url'));
            const fullUrl = window.location.origin + encodeURI(downloadUrl);
            
            // 创建弹窗
            const dialog = document.createElement('div');
            dialog.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.7);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
            `;
            
            // 弹窗内容
            const content = document.createElement('div');
            content.style.cssText = `
                background: white;
                padding: 20px;
                border-radius: 10px;
                text-align: center;
                max-width: 90%;
            `;
            
            const title = document.createElement('h5');
            title.textContent = '扫描下载文件';
            title.style.marginBottom = '15px';
            
            const qrCode = document.createElement('div');
            qrCode.id = 'download-qrcode';
            qrCode.style.margin = '0 auto';
            
            const closeBtn = document.createElement('button');
            closeBtn.className = 'btn btn-secondary mt-3';
            closeBtn.textContent = '关闭';
            closeBtn.onclick = () => document.body.removeChild(dialog);
            
            content.appendChild(title);
            content.appendChild(qrCode);
            content.appendChild(closeBtn);
            dialog.appendChild(content);
            document.body.appendChild(dialog);
            
            // 显示加载状态
            const loading = document.createElement('div');
            loading.className = 'qr-loading';
            loading.style.margin = '20px auto';
            content.insertBefore(loading, closeBtn);

            // 使用短链接API生成二维码
            const formData = new FormData();
            formData.append('url', fullUrl);
            
            fetch('/api/shorten/', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) throw new Error('网络响应不正常');
                return response.json();
            })
            .then(data => {
                content.removeChild(loading);
                if (data.shortUrl) {
                    new QRCode(document.getElementById("download-qrcode"), {
                        text: data.shortUrl,
                        width: 200,
                        height: 200,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                } else {
                    throw new Error(data.error || '短链接生成失败');
                }
            })
            .catch(error => {
                content.removeChild(loading);
                content.removeChild(qrCode);
                const errorMsg = document.createElement('p');
                errorMsg.textContent = '无法生成二维码: ' + error.message;
                errorMsg.style.color = 'red';
                content.insertBefore(errorMsg, closeBtn);
                
                // 回退方案：显示下载按钮
                const downloadBtn = document.createElement('a');
                downloadBtn.href = fullUrl;
                downloadBtn.className = 'btn btn-primary mt-2';
                downloadBtn.textContent = '直接下载';
                content.insertBefore(downloadBtn, closeBtn);
            });
        }

        function copyDownloadLink(element, url) {
            const fullUrl = window.location.origin + url;
            
            // 更安全的复制方法
            const copyToClipboard = (text) => {
                return new Promise((resolve, reject) => {
                    if (navigator.clipboard) {
                        navigator.clipboard.writeText(text).then(resolve).catch(reject);
                    } else {
                        try {
                            const textarea = document.createElement('textarea');
                            textarea.value = text;
                            textarea.style.position = 'fixed';
                            textarea.style.opacity = '0';
                            document.body.appendChild(textarea);
                            textarea.select();
                            const result = document.execCommand('copy');
                            document.body.removeChild(textarea);
                            result ? resolve() : reject();
                        } catch (err) {
                            reject(err);
                        }
                    }
                });
            };

            copyToClipboard(fullUrl)
                .then(() => {
                    // 简化反馈效果
                    const originalHtml = element.innerHTML;
                    element.innerHTML = '<i class="fa fa-check"></i>';
                    setTimeout(() => {
                        element.innerHTML = originalHtml;
                    }, 1000);
                })
                .catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制链接: ' + fullUrl);
                });
        }
    </script>
</body>
</html>